package com.ruyuan.dependency.order.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruyuan.dependency.order.entity.Order;
import com.ruyuan.dependency.order.service.OrderService;
import com.ruyuan.seckilling.common.QueueKey;
import com.ruyuan.seckilling.common.message.OrderCancelMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zhonghuashishan
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = QueueKey.QUEUE_CHECK_ORDER, consumerGroup = "checkOrderGroup")
public class CheckOrderListener implements RocketMQListener<Long> {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(Long orderId) {

        log.info("收到订单延时检查消息，orderId={}", orderId);

        Order order = orderService.queryById(orderId);

        // 用户还没有支付订单，自动取消订单
        if (!StringUtils.equals(order.getStatus(), Order.STATUS_PAYED)) {

            orderService.updataStatus(orderId, order.getStatus(), Order.STATUS_CANCELED);
            log.info("用户还没有支付订单，自动取消订单");

            // 发送一个订单被取消的消息
            JSONObject attributes = JSON.parseObject(order.getAttributes());
            String message = OrderCancelMessage.builder()
                    .sequence(attributes.getLong("sequence"))
                    .activityId(attributes.getLong("activityId"))
                    .userId(order.getUserId())
                    .skuId(order.getSkuId())
                    .count(order.getCount())
                    .build().toJsonString();
            rocketMQTemplate.convertAndSend(QueueKey.QUEUE_CANCEL_ORDER, message);
            log.info("发送订单取消的消息，message={}", message);
        }
    }
}
